<!--
 * @Description: 文件上传组件
 * @Author: huguodong
 * @Date: 2023-12-15 15:45:10
!-->
<template>
  <el-dialog v-model="dialogVisible" destroy-on-close draggable title="上传文件" width="600px">
    <el-upload
      ref="uploadRef"
      :action="uploadAction"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :headers="uploadHeaders"
      :on-error="handleError"
      :on-success="handleSuccess"
      class="upload-demo"
      drag
      multiple
    >
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">拖拽文件到此处或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">支持上传多个文件，单个文件大小不超过 100MB</div>
      </template>
    </el-upload>

    <template #footer>
      <el-button @click="onClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" name="fileUpload" setup>
import { UploadFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { UploadInstance, UploadUserFile, UploadProps } from "element-plus";
import { useUserStore } from "@/stores/modules";

const userStore = useUserStore();

// 对话框显示
const dialogVisible = ref(false);
// 上传地址
const uploadAction = ref(import.meta.env.VITE_API_URL + "/sys/dev/file/uploadLocal");
// 上传请求头
const uploadHeaders = ref({
  Authorization: `Bearer ${userStore.accessToken}`
});
// 上传实例
const uploadRef = ref<UploadInstance>();
// 文件列表
const fileList = ref<UploadUserFile[]>([]);

// 成功回调
let successCallback: (() => void) | null = null;

/**
 * 打开对话框
 */
function onOpen(callback?: () => void) {
  dialogVisible.value = true;
  fileList.value = [];
  successCallback = callback || null;
}

/**
 * 上传前校验
 */
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  const maxSize = 100 * 1024 * 1024; // 100MB
  if (rawFile.size > maxSize) {
    ElMessage.error(`文件大小不能超过 100MB!`);
    return false;
  }
  return true;
};

/**
 * 上传成功
 */
const handleSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  ElMessage.success(`文件 ${uploadFile.name} 上传成功`);
  // 执行回调刷新表格
  successCallback?.();
};

/**
 * 上传失败
 */
const handleError: UploadProps["onError"] = error => {
  ElMessage.error(`上传失败: ${error.message}`);
};

/**
 * 关闭对话框
 */
function onClose() {
  dialogVisible.value = false;
  fileList.value = [];
}

// 暴露方法
defineExpose({ onOpen, onClose });
</script>

<style lang="scss" scoped>
.upload-demo {
  width: 100%;
}

:deep(.el-upload-dragger) {
  padding: 20px 30px;
}

:deep(.el-icon--upload) {
  font-size: 28px;
  color: #409eff;
  margin-bottom: 8px;
}

:deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;

  em {
    color: #409eff;
    font-style: normal;
  }
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}
</style>
